package com.cancer.biz.weixin.service.impl;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.cancer.biz.weixin.service.VMenuService;
import com.cancer.common.util.WeixinUtil;

import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.json.JsonObject;
@Service
public class VMenuServiceImpl implements VMenuService {
	public static Logger logger = Logger.getLogger(VMenuServiceImpl.class);
	private final static Vertx vertx;
	static {
	    VertxOptions options = new VertxOptions();
		//最大执行时间10S,超过10s,讲触发警告
		options.setMaxEventLoopExecuteTime(10000000000L);
		vertx = Vertx.vertx(options);
	}
	@Override
	public Boolean createMenu(String jsonMenu) {
		Boolean flag = false;
		// 内存中获取token
		String token = WeixinUtil.currentToken.get("currentToken").toString();
		if (token != null) {
			// 调用接口创建菜单
			try{
				createMenu(jsonMenu, token);
				flag = true;
			}catch (Exception e) {
				logger.error("菜单创建失败，错误码：" + ExceptionUtils.getStackTrace(e));
			}
		}
		return flag;
	}
	/**
	 * 创建菜单
	 * 
	 * @param jsonMenu
	 *            菜单的json格式
	 * @param accessToken
	 *            有效的access_token
	 * @return 
	 * @return 
	 * @return 0表示成功，其他值表示失败
	 */
	private static void createMenu(String jsonMenu, String accessToken) {
		JsonObject jo = new JsonObject(jsonMenu);
		HttpClient http = vertx.createHttpClient(options);
		// 菜单创建（POST） 限100（次/天）
		String uri = "/cgi-bin/menu/create?access_token="+accessToken;
		//获取open id
        HttpClientRequest req = http.post(uri, resp -> {
            int scode = resp.statusCode();
            String msg = resp.statusMessage();
            resp.bodyHandler(buff -> {
                String body = buff.toString(WeixinUtil.STR_UTF8);
                if (scode >= 200 && scode < 300) {
                    //success
                	 JsonObject jsonObject = new JsonObject(body);
                	 if (null != jsonObject) {
             			if (0 != jsonObject.getInteger("errcode")) {
             				logger.error("创建菜单失败 errcode:" + jsonObject.getInteger("errcode")
             						+ "，errmsg:" + jsonObject.getString("errmsg"));
             			}
             		}
                } else {
                    logger.error("创建自定义菜单失败: " + msg);
                }
                http.close();
            });
        });
        req.setTimeout(5000);
        req.headers().set(HttpHeaders.CONTENT_TYPE, "application/json");
        req.exceptionHandler(ex -> {
        	 logger.error("创建自定义菜单失败: " + ExceptionUtils.getStackTrace(ex));
        });
        req.end(jo.encode(),WeixinUtil.STR_UTF8);
	}
}
